package edu.ncsu.csc.ip.client;

import java.io.IOException;
import java.net.ServerSocket;

import edu.ncsu.csc.ip.common.Log;

/**
 * This class takes in the client information and the rfcIndex
 * and it starts the rfc server. This contains an infinite loop
 * which will start a new thread once it accepts a connection.
 * 
 * 
 * @author Moin Ayazifar <mayazif@ncsu.edu>
 * @author Steven Elliott <sdelliot@ncsu.edu>
 * 
 */

public class RFCServer extends Thread {

	ClientInfo clientInfo;
	private RFCIndex rfcIndex;

	public RFCServer(ClientInfo clientInfo, RFCIndex rfcIndex) {
		this.clientInfo = clientInfo;
		this.rfcIndex = rfcIndex;
	}

	public void run() {
		ServerSocket serverSocket = null;

		boolean isListening = true;

		try {
			serverSocket = new ServerSocket(clientInfo.getRfcServerPort());

			Log.println(clientInfo + "RFC Server Listening on Port:"
					+ clientInfo.getRfcServerPort() + " ...");
			while (isListening) {
				// Listens for a connection to be made to this socket and
				// accepts it. The method blocks until a connection is made.
				new RFCServerThread(serverSocket.accept(), rfcIndex, clientInfo)
						.start();
			}
			serverSocket.close();
		} catch (IOException e) {
			Log.println(clientInfo + "RFC Server Could not listen on port: "
					+ clientInfo.getRfcServerPort() + ".");
			System.exit(-1);
		}
	}
}
